package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

//员工对象的业务层实现
@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    public List<String> listRoles(Long employeeId) {
        return roleMapper.selectStringRolesByEmployeeId(employeeId);
    }

    public List<String> listPermissions(Long employeeId) {
        return permissionMapper.selectByEmployeeId(employeeId);
    }

    public Employee getByName(String username) {
        return employeeMapper.selectByName(username);
    }

    public void batchDelete(Long[] ids) {
        employeeMapper.batchDelete(ids);
    }

    public boolean checkName(String name) {
        return employeeMapper.selectByName(name) == null;
    }

    public PageInfo<Employee> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Employee> list = employeeMapper.selectForList(qo);
        return new PageInfo<>(list);
    }

    public void saveOrUpdate(Employee entity, Long[] ids) {
        //先正常处理员工信息
        if (entity.getId() == null) {
            //先对密码加密再保存到数据库
            Md5Hash hash = new Md5Hash(entity.getPassword(), entity.getName());
            //重新设置加密后的密码
            entity.setPassword(hash.toString());
            employeeMapper.insert(entity);
        } else {
            //先删除当前对象跟角色的旧关系
            employeeMapper.deleteRelation(entity.getId());
            employeeMapper.updateByPrimaryKey(entity);
        }
        //再处理当前员工与角色的关系
        if (ids != null) {
            for (Long roleId : ids) {
                //把关系保存到中间表中
                employeeMapper.insertRelation(entity.getId(), roleId);
            }
        }
    }

    public void delete(Long id) {
        if (id != null) {
            //先删除关系,再删除员工对象
            employeeMapper.deleteRelation(id);
            employeeMapper.deleteByPrimaryKey(id);
        }
    }

    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }
}
